let http = require('http');
let fs = require('fs');
let url = require('url');
let path = require('path');

//读取文件的方法
function read(filepath,cb) {
    fs.readFile(path.resolve(__dirname,filepath),'utf-8',(err,data) => {
        if (err || data.length === 0) {
            cb([])
        } else {
            cb(JSON.parse(data))
        }
    })
}

//写入文件的方法
function write(filepath,data,cb) {
    fs.writeFile(path.resolve(__dirname,filepath),JSON.stringify(data),cb)
}

let PAGE_SIZE =6; //前台首页列表页分页时，后台每页返回6条
let server = http.createServer((req,res) => {
    //设置跨域头
    res.setHeader("Access-Control-Allow-Origin","*");
    res.setHeader("Access-Control-Allow-Headers","Content-Type,Content-Length,Authorization,Accept,X-Requested-With");
    res.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    if (req.method === "OPTIONS") return res.end();
    /**
     * 让options请求快速返回
     */
     let {pathname,query} = url.parse(req.url,true);

     //获取home轮播图和推荐等数据接口
     if (pathname === '/home/multidata'){
        read('./data/home/multidata.json',multidata => {
            res.setHeader('Content-Type','application/json;charset=utf-8')
            res.end(JSON.stringify(multidata))
        });
        return;
     }

     //获取home pop/new/sell分页数据
     if (pathname === '/home/data') {
        let type = query.type;
        let page = parseInt(query.page);
        switch (type) {
            case 'pop':
                read('./data/home/homedata-pop.json',list=> {
                    let resultList = list.slice((page-1)*PAGE_SIZE,page*PAGE_SIZE);
                    resultList={
                        "data":{
                            "isEnd":page===3,
                            "list":resultList,
                            "page":page
                        },
                        "returnCode":"1001",
                        "returnMessage":null,
                        "success":true
                    };
                    setTimeout(() => {
                        res.setHeader('Content-Type','application/json;charset=utf-8');
                        res.end(JSON.stringify(resultList))
                    },500)
                });
                break;
            case 'new':
                read('./data/home/homedata-new.json',list=> {
                    let resultList = list.slice((page-1)*PAGE_SIZE,page*PAGE_SIZE);
                    resultList={
                        "data":{
                            "isEnd":page===3,
                            "list":resultList,
                            "page":page
                        },
                        "returnCode":"1001",
                        "returnMessage":null,
                        "success":true
                    };
                    setTimeout(() => {
                        res.setHeader('Content-Type','application/json;charset=utf-8');
                        res.end(JSON.stringify(resultList))
                    },500)
                });
            break;
            case 'sell':
                read('./data/home/homedata-sell.json',list=> {
                    let resultList = list.slice((page-1)*PAGE_SIZE,page*PAGE_SIZE);
                    resultList={
                        "data":{
                            "isEnd":page===3,
                            "list":resultList,
                            "page":page
                        },
                        "returnCode":"1001",
                        "returnMessage":null,
                        "success":true
                    };
                    setTimeout(() => {
                        res.setHeader('Content-Type','application/json;charset=utf-8');
                        res.end(JSON.stringify(resultList))
                    },500)
                });
            break;
        }
        return;
     }

     //获取商品详情页
     if (pathname === '/detail') {
        let iid = query.iid;
        read('./data/detail/detail.json',goods=>{
            let targetGoods = goods.find(item=>item.iid === iid)
            res.setHeader('Content-Type','application/json;charset=utf-8')
            res.end(JSON.stringify(targetGoods))
        })
        return
     }
     
     //获取详情页推荐数据
     if (pathname === '/recommend') {
        read('./data/detail/recommend.json',recommends => {
            res.setHeader('Content-Type','application/json;charset=utf-8')
            res.end(JSON.stringify(recommends))
        })
        return
     }

     //获取分类页面需要的主分类数据
     if (pathname === '/category') {
        read('./data/category/category.json',categories => {
            res.setHeader('Content-Type','application/json;charset=utf-8')
            res.end(JSON.stringify(categories))
        })
        return
     }

     //获取分类页面需要的侧分类数据
     if (pathname === '/subcategory') {
        read('./data/category/subcategory.json',subcategories => {
            res.setHeader('Content-Type','application/json;charset=utf-8')
            res.end(JSON.stringify(subcategories))
        })
        return
     }


    //开启静态服务
    fs.stat('.'+pathname,(err,stats) => {
        if (err) {
            let p = path.join(__dirname+"/index.html")
            fs.createReadStream(p).pipe(res)
        } else {
            if (stats.isDirectory()) {
                let p = path.join('.'+pathname,'./index.html')
                fs.createReadStream(p).pipe(res)
            } else {
                fs.createReadStream('.'+pathname).pipe(res)
            }
        }
    });
})



server.listen(3000,() => {
    console.log('server is running at port 3000...')
})